package com.example.mes_common.result;

import com.example.mes_common.interfaces.NoWrap;
import com.example.mes_common.utils.JacksonUtils;
import com.example.mes_common.utils.ResultTool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = "com.example.*") // 指定拦截的包
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        // 排除已封装的结果或标记了@NoWrap注解的方法
        return !returnType.getParameterType().equals(JsonResult.class)
                && !returnType.hasMethodAnnotation(NoWrap.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 处理String类型返回值（需手动转JSON）
        if (body instanceof String) {
            return JacksonUtils.toJson(ResultTool.success(body)); // 使用你的JSON工具类
        }
        // 其他类型直接封装
        return ResultTool.success(body);
    }
}
